#!/usr/bin/env python
from request_handler import RequestHandler

import socket
import SocketServer
import BaseHTTPServer

__all__ = ("Server", "serve_forever")

class Server(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):

    run = True

    def get_request(self):
        sock = self.socket
        old = sock.gettimeout()
        sock.settimeout(0.5)
        sock.setblocking(1)
        while self.run:
            try:
                connection = sock.accept()
                sock.settimeout(old)
                return connection
            except socket.timeout, e:
                pass
        raise socket.error("Not running")
    # get_request()


    def serve_forever(self):
        try:
            while self.run:
                self.handle_request()
        except KeyboardInterrupt, e:
            pass
        self.server_close()
    # serve_forever()


    def server_close(self):
        self.run = False
        BaseHTTPServer.HTTPServer.server_close(self)
    # server_close()

#class Server


def serve_forever(host='', port=2323):
    print "Server Online..."
    address = (host, port)
    RequestHandler.protocol_version = "HTTP/1.0"
    sonar = Server(address, RequestHandler)
    sonar.serve_forever()
# server_forever(host, port)



if __name__ == '__main__':
    serve_forever()